<?php
namespace backend\components;
use yii;
use yii\base\Object;
use yii\web\UploadedFile;
use backend\models\Files;
class Upload extends Object{
    
    public function Upload($model){
    	if(Yii::$app->request->isPost){
			$model->files = UploadedFile::getInstances($model, 'files');

			if ($model->files) {
				$fileIdList = null;
	            foreach ($model->files as $file) {
	            	//处理目录
	            	$path = 'uploads';
	            	$userPath = Yii::$app->user->getId();
	            	$uid = $userPath;
	            	$common = trim(Yii::getAlias('@common'), '/');
	            	$path = trim($path.'/'.$userPath.'/'.date('Ymd'), '/');
	            	$pathArr = explode('/', $path);
	            	$tempPath = null;
	            	/** 会出现异常的地方 由PHP发出 Yii 默认会捕捉**/
	            	if(!is_dir($common . '/'  . $path)){
                        foreach ($pathArr as $temp) {
                            $tempPath.='/'.$temp;

                            if(!is_dir($common.$tempPath)){
                                mkdir($common.$tempPath);
                            }
                        }
                    }
	            	/** 会出现异常的地方 **/

	            	//保存
	            	if($file->saveAs($common .'/'. $path .'/'. $file->name)){
	            		//并更新数据库
	            		if($res = $this->insert($file->name, $file->size, $file->extension, '/common/' . $path . '/', time(), $uid)){
	            			/** 会出现异常的地方 **/
	            			$fileIdList[] = $res->id;
	            			/** 会出现异常的地方 **/
	            		}else{
	            			
	            			return $message['error'] = '异常错误!';
	            		}
	            	}else{
	            		return $message['error'] = '保存失败!';
	            	}
	            }
                return $fileIdList;
	        }else{
	        	return $message['error'] = '文件错误!';
	        }
		}
    }


    public function insert($name, $size, $extension, $path, $create_time, $uid){
		$model = new Files;
		$model->scenario = 'create';
		$model->name = $name;
		$model->size = $size;
		$model->extension = $extension;
		$model->path = $path;
		$model->create_time = $create_time;
		$model->uid = $uid;

		if(!$model->save()){
			/**
			 * 不是预期效果 异常处理
			 */
			return $model;
		}
		return $model;
	}
}